package com.fin.quant.domain.repository.impl;

import com.fin.quant.common.TargetType;
import com.fin.quant.domain.entity.TargetMetricsEntity;
import com.fin.quant.domain.mapstruct.TagMapperStruct;
import com.fin.quant.domain.repository.TargetMetricsRepository;
import com.fin.quant.instra.mysql.mapper.TargetMetricsMapper;
import com.fin.quant.instra.mysql.model.TargetMetrics;
import com.fin.quant.instra.mysql.model.TargetMetricsExample;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 目标指标仓储实现
 */
@Service
@Slf4j
public class TargetMetricsRepositoryImpl implements TargetMetricsRepository {

    @Autowired
    private TargetMetricsMapper targetMetricsMapper;

    @Override
    public Map<Long, List<TargetMetricsEntity>> getAssetMetricsMap(List<Long> assetIdList) {
        if (CollectionUtils.isEmpty(assetIdList)) {
            return Collections.emptyMap();
        }

        try {
            // 查询资产指标
            TargetMetricsExample example = new TargetMetricsExample();
            example.createCriteria().andTargetIdIn(assetIdList)
                    .andTargetTypeEqualTo(TargetType.asset.getType());
            List<TargetMetrics> targetMetrics = targetMetricsMapper.selectByExample(example);

            if (CollectionUtils.isEmpty(targetMetrics)) {
                return Collections.emptyMap();
            }

            // 按目标ID分组指标
            return targetMetrics.stream()
                    .map(TagMapperStruct.INSTANCE::model2Entity)
                    .collect(Collectors.groupingBy(TargetMetricsEntity::getTargetId));
        } catch (Exception e) {
            log.error("获取资产指标映射失败, assetIdList: {}", assetIdList, e);
            return Collections.emptyMap();
        }
    }
}
